package cn.itcast.bos.service.base.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.base.OrderRepository;
import cn.itcast.bos.dao.base.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.base.OrderService;
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private WorkBillRepository workBillRepository;
	//注入发短信的队列
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Override
	public void addOrder(Order order) {
		//设置订单时间
		order.setOrderTime(new Date());
		order.setOrderNum(UUID.randomUUID().toString());
		order.setStatus("1");// 1,待取件
		//寄件人省市区
		Area area = order.getSendArea();
		Area persistArea=areaRepository.findByProvinceAndCityAndDistrict(area.getProvince(),area.getCity(),area.getDistrict());
		//收件人省市区
		Area recArea=new Area();
		Area persistRecArea=areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(),recArea.getCity(),recArea.getDistrict());
		
		//存入订单中
		order.setRecArea(persistRecArea);
		order.setSendArea(persistArea);
		
		
		System.err.println(order);
		String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/findFixedAreaIdByAddress?address="+order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if(fixedAreaId!=null){
			FixedArea fixedArea =fixedAreaRepository.findOne(fixedAreaId);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if(iterator.hasNext()){
				Courier courier=iterator.next();
				if(courier!=null){
					//自动分单成功
					System.out.println("自动分单成功.....");
					//将快递员关联订单
					order.setCourier(courier);
					//保存订单
					orderRepository.save(order);
					//生成工单,发送短信
					generateWorkBill(order);
					return;
				}
			}
		}
		//基于分单逻辑 查询省市区 查询分区关键字  匹配地址  基于分区实现自动分单   分区主关键字
		for (SubArea subArea : persistArea.getSubareas()) {
			if(order.getSendAddress().contains(subArea.getKeyWords())){
				//找到分区,找到定区,找到快递员
				Courier courier = subArea.getFixedArea().getCouriers().iterator().next();
				if(courier!=null){
					//自动分单成功
					System.out.println("分区主关键字自动分单成功");
					//将快递员关联到订单上
					order.setCourier(courier);
					//保存订单
					//设置自动分单
					order.setOrderType("1");  //1,是自动分单
					order.setOrderNum(UUID.randomUUID().toString());
					orderRepository.save(order);
					//生成工单,发送短信
					generateWorkBill(order);
					
					return;
				}
			}
			
		}
		///分区辅助关键字
		for (SubArea subArea : persistArea.getSubareas()) {
			if(order.getSendAddress().contains(subArea.getAssistKeyWords())){
				//找到分区,找到定区,找到快递员
				/*
				 * Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if(iterator.hasNext()){
				Courier courier=iterator.next();
				if(courier!=null){
					//自动分单成功
					System.out.println("自动分单成功.....");
					//将快递员关联订单
					order.setCourier(courier);
					//保存订单
					orderRepository.save(order);
					//生成工单,发送短信
					generateWorkBill(order);
					return;
				}
			}
			
				 * */
				Courier courier = subArea.getFixedArea().getCouriers().iterator().next();
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if(iterator.hasNext()){
					if(courier!=null){
						//自动分单成功
						System.out.println("分区辅助关键字自动分单成功");
						//将快递员关联到订单上
						order.setCourier(courier);
						//保存订单
						//设置自动分单
						order.setOrderType("1");   //1是自动分单
						orderRepository.save(order);
						//生成工单,发送短信
						generateWorkBill(order);
						return;
					}
				}
			}
			
		}
		//人工分单
		order.setOrderType("2");//人工分单
		orderRepository.save(order);
	}
	//生成工单,发送短信的方法
	private void generateWorkBill(final Order order) {
		WorkBill workBill=new WorkBill();
		workBill.setBuildtime(new Date());
		workBill.setCourier(order.getCourier());
		workBill.setPickstate("新单");
		workBill.setOrder(order);
		workBill.setType("新");
		workBill.setRemark(order.getRemark());
		//生成短信的序号
		final String smsNumber=RandomStringUtils.randomNumeric(4);
		System.out.println(smsNumber);
		workBill.setSmsNumber(smsNumber);
		
		workBillRepository.save(workBill);
		//发送短信
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage=session.createMapMessage();
				mapMessage.setString("telephone",order.getCourier().getTelephone());
				//短信序号,取件地址,联系人,手机,快递员捎话,
				mapMessage.setString("msg","短信序号:"+smsNumber+",取件地址是:"+order.getSendAddress()
						+",联系人是:"+order.getSendName()+",手机是:"+order.getSendMobile()+",快递员捎话是"+order.getSendMobileMsg());
				return mapMessage;
			}
		});
		
		
		//修改订单状态
		workBill.setPickstate("已通知");
		
		
	}
	@Override
	public Order findByOrderNum(String orderNum) {
		// TODO Auto-generated method stub
		return orderRepository.findByOrderNum(orderNum);
	}

}
